package com.sunxu.designpatterns.patterns.creational.singleton;

/**
 * @author 孙许
 * @date 2018-08-22
 * @description 双重锁检查
 * volatile防止指令重排序
 */
public class LazyDoubleCheckSingleton {

    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton;

    private LazyDoubleCheckSingleton() {

    }

    public static LazyDoubleCheckSingleton getInstance() {
        if (lazyDoubleCheckSingleton == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (lazyDoubleCheckSingleton == null) {
                    // 1.分配内存给这个对象
                    // 2.初始化对象
                    // 3.设置变量指向刚分配的内存地址
                    // 2和3可能重排序
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton();
                }
            }
        }
        return lazyDoubleCheckSingleton;
    }
}
